from django.contrib.auth.backends import ModelBackend
import re

from users.models import User


class AutoUser(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
       #判断用户中是否存在手机号
       try:
           if re.match(r'1[3-9]\d{9}',username):
               user = User.objects.get(mobile=username)
            #通过用户名查询用户
           else:
               user = User.objects.get(username=username)
       except User.DoesNotExist:
           return None

       return user